<?php
class LoginHandler extends CI_Model{
	function doLogin($username, $password){
		$this->load->model('userDAL');
		//$login = $this->userDAL->validLogin($username, md5($password));
		$login = $this->pass($username, $password);
		// If login succeded set session variable
		if($login){
			$data = array(
    			USERNAME=>$username,
    			IS_LOGGED_IN=>TRUE	
    			);
    		$this->session->set_userdata($data);
    	}
		return $login;
	}
	function doLogout(){
		// Unset session variable
		$data = array(
    			USERNAME=>'',
    			IS_LOGGED_IN=>''
    		);
    	$this->session->unset_userdata($data);
	}
	function isLoggedIn(){
		// Get loginstatus
    	$this->isLoggedIn = $this->session->userdata(IS_LOGGED_IN);
    	// Check session variabel and cookies - return true if loginstatus is set to true in either of them
    	if($this->isLoggedIn == TRUE || $this->getLoginCookie() == TRUE){
    		return TRUE;
    	}
    	else{
    		return FALSE;
    	}
	}
	function getLoginCookie(){
    	$this->load->helper('cookie');
    	if(get_cookie(IS_LOGGED_IN)){
    		return TRUE;
    	}
    	else{
    		return FALSE;
    	}
    }
    function pass($username, $inputPassword){
    	$this->load->model('userDAL');
    	// Get password
    	$passwordFromDb = $this->userDAL->getPassword($username);
    	// Substring salt
    	$salt = substr($passwordFromDb, 0, 40);
    	// Hash input password
    	$iph = $salt . $inputPassword;
		$iph = hash('sha1', $iph);
		$iph = $salt . $iph;
		if($iph == $passwordFromDb){
			return TRUE;
		}
		else {
			return FALSE;
		}
    }
}
